package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class AccountService {
    @Autowired
    private AccountDao accountDao;

    @Transactional
    public void transfer(Long fromAccountId, Long toAccountId, BigDecimal amount) {
        if (fromAccountId.equals(toAccountId)) {
            throw new IllegalArgumentException("转出账户和转入账户不能相同");
        }
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("转账金额必须大于0");
        }

        boolean outSuccess = accountDao.outMoney(fromAccountId, amount);
        if (!outSuccess) {
            throw new RuntimeException("余额不足或账户不存在");
        }

        boolean inSuccess = accountDao.inMoney(toAccountId, amount);
        if (!inSuccess) {
            throw new RuntimeException("转入账户不存在");
        }
    }
}